/*
 * @Author: whq
 * @Date: 2025-08-04 14:25:24
 * @LastEditTime: 2025-08-05 16:35:01
 * @LastEditors: whq
 * @Description:
 * @FilePath: /app/src/utils/request.ts
 */
import { getToken, clearAll } from "@/utils/cache";
import { ResultCodeEnum } from "@/enums/ResultCodeEnum";
import { isPlainObject } from ".";
import { clone } from 'radash'

const responseConfig = {
  success: (response: any, resolve: any, reject: any) => {
    console.log(response)
    // 业务状态码 00000 表示成功
    if (response.statusCode == ResultCodeEnum.SUCCESS) {
      resolve(response.data);
    }
    // 令牌失效或过期处理
    else if (response.code == ResultCodeEnum.TOKEN_INVALID) {
      console.log("令牌失效或过期处理");
      clearAll();
      // 跳转到登录页
      uni.reLaunch({
        url: "/pages/login/index",
      });
    } else {
      // 其他业务处理失败
      uni.showToast({
        title: response.msg || "业务处理失败",
        icon: "none",
      });
      reject({
        message: response.msg || "业务处理失败",
        code: response.code,
      });
    }
    // const resData = response as ResponseData<T>;
    // if (resData.statusCode === ResultCodeEnum.SUCCESS) {
    //   resolve(resData.data);
    // }
    // // 令牌失效或过期处理
    // else if (resData.code === ResultCodeEnum.TOKEN_INVALID) {
    //   console.log("令牌失效或过期处理");
    //   clearAll();
    //   // 跳转到登录页
    //   uni.reLaunch({
    //     url: "/pages/login/index",
    //   });
    // } else {
    //   // 其他业务处理失败
    //   uni.showToast({
    //     title: resData.msg || "业务处理失败",
    //     icon: "none",
    //   });
    //   reject({
    //     message: resData.msg || "业务处理失败",
    //     code: resData.code,
    //   });
    // }
  },
  fail: (error: any, reject: any) => {
    console.log("fail error", error);
    uni.showToast({
      title: "网络请求失败",
      icon: "none",
      duration: 2000,
    });
    reject({
      message: "网络请求失败",
      error,
    });
  },
}

export interface OtherParams {
  type?: 'image',
  isAdminApi?: boolean
}

export default function request<T>(cOptions: UniApp.RequestOptions, otherParams?: OtherParams): Promise<T> {
  // H5 使用 VITE_APP_BASE_API 作为代理路径，其他平台使用 VITE_APP_API_URL 作为请求路径
  let baseApi = import.meta.env.VITE_APP_API_URL;
  // #ifdef H5
  baseApi = import.meta.env.VITE_APP_BASE_API + `/api/${otherParams?.isAdminApi ? 'admin' : 'web'}`;
  // #endif

  return new Promise((resolve, reject) => {
    const token = '123321'
    const options = clone(cOptions)
    if (isPlainObject(options.data)) {
      (options.data as AnyObject)['token'] = token
    }

    if (otherParams?.type) {
      uni.uploadFile({
        url: `${baseApi}${options.url}`, //仅为示例，非真实的接口地址
        filePath: options.data as string,
        name: otherParams.type,
        formData: {token},
        success: (res) => {
          responseConfig.success(res, resolve, reject)
        },
        fail: (err) => {
          responseConfig.fail(err, reject)
        }
      });
    } else {
      uni.request({
        ...options,
        url: `${baseApi}${options.url}`,
        header: {
          ...options.header,
          // Authorization: getToken() ? `Bearer ${getToken()}` : "",
        },
        success: (res) => {
          responseConfig.success(res, resolve, reject)
        },
        fail: (err) => {
          responseConfig.fail(err, reject)
        }
      });
    }
    
  });
}
